<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>选择排序</title>
  </head>
  <body>
    <div>
      选择排序算法是一种原址比较排序算法。选择排序大致的思路是找到数据结构中的最小值并
      <br />
      将其放置在第一位，接着找到第二小的值并将其放在第二位，以此类推。
    </div>
    <img src="../../../image/排序/选择排序.png" alt="" srcset="">
    <script>
      function swap(array, index1, index2) {
        [array[index1], array[index2]] = [array[index2], array[index1]];
        return array;
      }

      var arr = [31, 12, 24, 5, 6, 84, 3, 5, 323, 79, 45, 2, 21, 78, 31];

      function selectSort(array) {
        console.time("选择排序")
        var length = array.length;
        var indexMin;
        for (var i = 0; i < length - 1; i++) {
          indexMin = i;
          for (var j = i; j < length; j++) {
            if (array[indexMin] > array[j]) {
              indexMin = j;
            }
          }
          if (i !== indexMin) {
            array = swap(array, i, indexMin);
          }
        }
        console.timeEnd("选择排序")
        return array;
      }

      console.log(selectSort(arr));  // [2, 3, 5, 5, 6, 12, 21, 24, 31, 31, 45, 78, 79, 84, 323]
    </script>
  </body>
</html>
